package com.zyf.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyf.common.excption.YyghException;
import com.zyf.common.result.ResultCodeEnum;
import com.zyf.enums.AuthStatusEnum;
import com.zyf.helper.JwtHelper;
import com.zyf.mapper.UserInfoMapper;
import com.zyf.model.user.Patient;
import com.zyf.model.user.UserInfo;
import com.zyf.service.PatientService;
import com.zyf.service.UserinfoService;
import com.zyf.vo.user.LoginVo;
import com.zyf.vo.user.UserAuthVo;
import com.zyf.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 用户的业务层实现类
 * @author zyf
 * @date 2021年05月18日 11:32
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserinfoService {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    /**
     * 用户手机号登录
     * @author zyf
     * @date 2021/5/18 11:48
     * @param loginVo  用户登录VO类
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        Map<String, Object> map = new HashMap<>();
        //从loginVo中获取输入的手机和验证码
        String phone = loginVo.getPhone();//手机号
        String code = loginVo.getCode(); //验证码
        //判断手机号和验证码是否为空
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        // 验证验证码是否正确
        String reidsCode = redisTemplate.opsForValue().get(phone);
        if (!code.equalsIgnoreCase(reidsCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //微信登录绑定手机号
        UserInfo userInfo =null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())){
            userInfo  = this.selectWxInfoOpenid(loginVo.getOpenid());
            if (null != userInfo){
                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("phone",phone);
                UserInfo userInfo1 = baseMapper.selectOne(wrapper);
                if (userInfo1!=null && userInfo1.getOpenid() == null){
                    userInfo1.setOpenid(userInfo.getOpenid())
                            .setPhone(loginVo.getPhone())
                            .setNickName(userInfo.getNickName())
                            .setStatus(userInfo.getStatus());
                    baseMapper.deleteById(userInfo);
                    baseMapper.updateById(userInfo1);
                }else if(userInfo1 != null){
                    map.put("code",ResultCodeEnum.REGISTER_WEIXIN_ERROR);
                    return map;
                }
                userInfo.setPhone(loginVo.getPhone());
                baseMapper.updateById(userInfo);
            }else {
                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("openid",loginVo.getOpenid());
                baseMapper.delete(wrapper);
                map.put("code",ResultCodeEnum.DATA_ERROR);
                return map;

            }
        }

        //如果userInfo为空 进行正常的手机登录
        if (userInfo == null){
            //判断是否第一次登录： 根据手机号查询数据库，如果不存在就是第一次登录，进行注册
            QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("phone",phone);
            userInfo = baseMapper.selectOne(wrapper1);
            if (userInfo == null) {//第一次使用这个手机号
                userInfo = new UserInfo();
                userInfo.setName("")
                        .setPhone(phone)
                        .setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        //判断用户是否被禁用
        if (userInfo.getStatus() == 0){
            throw  new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //不是第一次就直接登录
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        //返回信息， 返回登录用户名，返回token
        map.put("name",name);
        // jwt生成token生成
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        map.put("code","200");
        return map;
    }

    /**
     * 手机号重新绑定微信
     * @author zyf
     * @date 2021/6/5 14:42
     * @param loginVo
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> rebinding(LoginVo loginVo) {
        QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("phone",loginVo.getPhone());
        UserInfo userInfo = baseMapper.selectOne(wrapper1);
        if (null == userInfo){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        baseMapper.deleteById(userInfo);
        Map<String, Object> map = this.loginUser(loginVo);
        return map;
    }

    /**
     * 删除过期用户
     * @author zyf
     * @date 2021/6/5 15:08
     * @param loginVo
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public void deleteUserFile(LoginVo loginVo) {
        QueryWrapper<UserInfo> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("openid",loginVo.getOpenid());
        baseMapper.delete(wrapper3);
    }

    /**
     * 判断数据库中是否存在微信扫描人的信息， 根据openid判断
     * @author zyf
     * @date 2021/5/19 17:58
     * @param openid  openid
     * @return com.zyf.model.user.UserInfo
     */
    @Override
    public UserInfo selectWxInfoOpenid(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    /**
     * 用户认证Api
     * @author zyf
     * @date 2021/5/25 20:35
     * @param userId 用户id
     * @param userAuthVo 用户认证数据vo对象
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id，查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        userInfo.setName(userAuthVo.getName())
                .setCertificatesType(userAuthVo.getCertificatesType())
                .setCertificatesNo(userAuthVo.getCertificatesNo())
                .setCertificatesPositiveUrl(userAuthVo.getCertificatesPositiveUrl())
                .setCertificatesBackUrl(userAuthVo.getCertificatesBackUrl())
                .setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    /**
     * 分页条件查询用户信息Api
     * @author zyf
     * @date 2021/5/28 14:38
     * @param pageParam 分页参数
     * @param userInfoQueryVo 条件查询参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.zyf.model.user.UserInfo>
     */
    @Override
    public IPage<UserInfo> selectUserByPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间

        //对条件值进行非判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if (!StringUtils.isEmpty(authStatus)){
            wrapper.eq("auth_status",authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }

        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        //编号转换成对应的值
        userInfoPage.getRecords().stream().forEach(this::packageUserInfo);
        return userInfoPage;
    }

    /**
     * 用户锁定
     * @author zyf
     * @date 2021/5/28 15:42
     * @param userId 用户id
     * @param status 用户状态
     */
    @Override
    public void lockUser(Long userId, Integer status) {
        if (status.intValue()==0 || status.intValue() ==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 用户详情
     * @author zyf
     * @date 2021/5/28 16:17
     * @param userId 用户id
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> showUser(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //根据userId查询出用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据用户Id查询出就诊人的信息
        List<Patient> patientList = patientService.findAllPatientByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    /**
     * 认证审批
     * @author zyf
     * @date 2021/5/28 17:53
     * @param userId 用户id
     * @param authStatus 用户认证状态
     */
    @Override
    public void approval(Long userId, Integer authStatus) {
       if (authStatus.intValue() ==2 || authStatus.intValue() ==-1){
           UserInfo userInfo = baseMapper.selectById(userId);
           userInfo.setAuthStatus(authStatus);
           baseMapper.updateById(userInfo);
       }
    }



    /**
     * 编号转换成对应的值
     * @author zyf
     * @date 2021/5/28 15:07
     * @param userInfo 用户
     */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getStatus()));

        //用户状态
        String statusString = userInfo.getStatus() ==0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
